export default class SocketService {
	//单例
	static instance = null
	static get Instance() {
		if (!this.instance) {
			this.instance = new SocketService()
		}
		return this.instance
	}
	//和服务端连接的socket对象
	ws = null
	//存储回调函数
	callBackMapping = {

	}
	//标识是否连接成功
	connected = false
	connect() {
		//连接服务器
		if (!window.WebSocket) {
			return console.log('你的浏览器不支持websocket')
		}
		this.ws = new WebSocket('ws://localhost:9998')
		//连接成功的事件
		this.ws.onopen = () => {
			console.log('连接服务端成功')
			this.connected = true
		}
		//连接服务端失败的事件
		this.ws.onclose = () => {
			console.log('连接服务端失败')
			this.connected = false
		}
		//得到服务端数据发送多过来的数据
		this.ws.onmessage = msg => {
			console.log('从服务端获取到了数据')
			//真正服务端发送过来的原始数据时在msg中的data字段
			//console.log(msg.data)
			const recvData = JSON.parse(msg.data)
			const socketType = recvData.socketType
			//判断回调函数是否存在
			if (this.callBackMapping[socketType]) {
				const action = recvData.action
				if (action === 'getData') {
					const realData = JSON.parse(realData.data)
					this.callBackMapping[socketType].call(this, realData)
				} else if (action === 'fullScreen') {
					console.log('mn')
				} else if (action === 'themeChange') {
					console.log('mn')
				}
			}
		}
	}
	//回调函数的注册
	registerCallBack(socketType, callBack) {
		this.callBackMapping[socketType] = callBack
	}
	//回调函数的取消
	unRegistserCallBack(socketType) {
		this.callBackMapping[socketType] = null
	}
	//发送数据的方法
	send(data) {
		//判断此时时连接成功
		if (this.connected) {
			this.ws.send(JSON.stringify(data))

		} else {
			setTimeout(() => {
				this.send(data)
			}, 500)
		}
	}
}
